#include "ad_usermgrlist.h"
#include "ui_ad_usermgrlist.h"

#include "ad_userinfo.h"

#include <QAbstractItemView>
#include <QMessageBox>

AD_userMgrList::AD_userMgrList(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AD_userMgrList)
{
    ui->setupUi(this);

    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);


    TOOLS->setTableHead(ui->tableWidget,{"姓名","账号","密码","管理员","教师","辅导员"});
}

AD_userMgrList::~AD_userMgrList()
{
    delete ui;
}

void AD_userMgrList::updateTabel()
{
    auto data = DB->getAllUserInfo("isStudent = 0");
    setDataToTabel(data);
}

void AD_userMgrList::setDataToTabel(const QList<DB_userInfo> &data)
{
    m_data = data;

    ui->tableWidget->setRowCount(data.count());

    for(int r = 0;r<data.count() ; r++){
        auto&& cur = data[r];

        QString info = "%0,%1,%2,%3,%4,%5";
        info = info.arg(cur.name)
                .arg(cur.account)
                .arg(cur.pwd)
                .arg(cur.isAdmin==1?"是":"否")
                .arg(cur.isTeacher==1?"是":"否")
                .arg(cur.isCounselor==1?"是":"否");

        QStringList curStrs = info.split(",");

        for(int c = 0 ; c< curStrs.count();c++){
            ui->tableWidget->setItem(r,c,new  QTableWidgetItem(curStrs[c]));
        }
    }
}

int AD_userMgrList::getCurAccount()
{
    auto row = ui->tableWidget->currentRow();
    if(row < 0 || row >= ui->tableWidget->rowCount()){
        QMessageBox::about(nullptr,"未选择行","未选择行");
        return -1;
    }

    int account = ui->tableWidget->model()->index(row,1).data().toString().toInt();
    return account;
}

void AD_userMgrList::showEvent(QShowEvent *event)
{
    updateTabel();
    QWidget::showEvent(event);
}

void AD_userMgrList::on_pushButton_clicked()
{
    PAGEJUMP->setPage(DK_AD_UserInfo);

    auto wgt = qobject_cast<AD_UserInfo*>(PAGEJUMP->getPage(DK_AD_UserInfo));
    if(wgt){
        wgt->setData(DB_userInfo());
    }

}

void AD_userMgrList::on_pushButton_2_clicked()
{
    int account = getCurAccount();
    for(auto&& item:m_data){
        if(item.account == account){
            item.deleteOne();
            QMessageBox::about(nullptr,"删除成功","删除成功");
            break;
        }
    }

    updateTabel();
}


void AD_userMgrList::on_pushButton_3_clicked()
{
    PAGEJUMP->setPage(DK_AD_UserInfo);

    int account = getCurAccount();

    auto wgt = qobject_cast<AD_UserInfo*>(PAGEJUMP->getPage(DK_AD_UserInfo));
    if(wgt){
        wgt->setDataByAccount(account);
    }
}

